const { Router } = require("express");
const User = require("../model/User");
const md5 = require("md5");
const multer = require("multer");
const router = new Router();

router.use(require("../middleware/auth.js"));
//http://localhost:8000/api/user
//获取用户的所有数据
// User.create({
//   username: "admin",
//   password: "admin",
//   telephone: 13467341601,
//   RegTime: "2023-07-25 17:36:56",
//   LogTime: "2023-07-30 17:36:57",
//   consumption: 6666,
//   goods: 66,
// });
router.get("/all", async (req, res) => {
  const user_id = req.userInfo._id;
  //执行更新
  const data = await User.find(
    { _id: user_id },
    { __v: false, password: false }
  );
  // 响应客户端
  res.status(200).json({ message: "ok", data });
});

//修改用户个人信息
router.patch("/edit", async (req, res) => {
  const { nikename } = req.body;
  const user_id = req.userInfo._id;
  try {
    const user = await User.findByIdAndUpdate(
      user_id,
      {
        nikename,
      },
      { projection: { avatar: 0, password: 0, __v: 0 }, new: true }
    );
    res.status(200).json({ msg: "信息修改成功", user });
  } catch (error) {
    res.json({ msg: "服务器错误", error });
  }
});
//修改用户密码
router.patch("/change", async (req, res) => {
  try {
    const user_id = req.userInfo._id;
    const { oldpassword, newpassword } = req.body;
    const user = await User.findById(user_id);
    if (user.password == md5(oldpassword)) {
      user.password = md5(newpassword);
      await user.save();
      res.json({ msg: "密码修改成功" });
    } else {
      res.json({ msg: "输入密码与原密码不一致" });
    }
  } catch (error) {
    res.status(500).json({ msg: "服务器错误" });
  }
});

//获取所有用户的数据
router.get("/GetAll", async (req, res) => {
  try {
    const data = await User.find();
    res.send({
      state: true,
      code: 200,
      msg: data,
    });
  } catch (error) {
    console.log(error);
    res.send({
      state: false,
      code: 400,
      msg: "请求出错",
    });
  }
});
module.exports = router;
